﻿$(document).ready(function(){
    //资质文件轮换 start
    $(".proCarousel").slidelf1({
        "prev":"turnLCarousel",
        "next":"turnRCarousel",
        "speed":500
    });
    //资质文件轮换 end
    /*3C关联方案*/
    $(".container1").hScrollPane({
        mover:"ul",
        moverW:function(){return $(".container1 li").length*210;}(),
        showArrow:false,
        handleCssAlter:"draghandlealter1",
        mousewheel:{moveLength:100},
        scrollClass:"hScrollPane_dragbar1",
        scrollChildClass:"hScrollPane_draghandle1"
    });
    $(".container2").hScrollPane({
            mover:"ul",
            moverW:function(){return $(".container2 ol").length*220;}(),
            showArrow:false,
            handleCssAlter:"draghandlealter2",
            mousewheel:{moveLength:100},
            scrollClass:"hScrollPane_dragbar2",
            scrollChildClass:"hScrollPane_draghandle2"
        });
    $(".minute_menu0 li").click(function(){
        var minuteIndex = $(this).index();
        $(".minute_menu0 a").removeClass("cur");
        $(".minute_menu0 a:eq("+minuteIndex+")").addClass("cur");
        $(".taocan").hide();
        $(".taocan:eq("+minuteIndex+")").show();
    });
//    $(".container3").hScrollPane({
//        mover:"ol",
//        moverW:function(){return $(".container3 li").length*220;}(),
//        showArrow:false,
//        handleCssAlter:"draghandlealter3",
//        mousewheel:{moveLength:100},
//        scrollClass:"hScrollPane_dragbar3",
//        scrollChildClass:"hScrollPane_draghandle3"
//    });
//    $(".container4").hScrollPane({
//        mover:"ol",
//        moverW:function(){return $(".container4 li").length*220;}(),
//        showArrow:false,
//        handleCssAlter:"draghandlealter4",
//        mousewheel:{moveLength:100},
//        scrollClass:"hScrollPane_dragbar4",
//        scrollChildClass:"hScrollPane_draghandle4"
//    });
//    $(".container5").hScrollPane({
//        mover:"ol",
//        moverW:function(){return $(".container5 li").length*220;}(),
//        showArrow:false,
//        handleCssAlter:"draghandlealter5",
//        mousewheel:{moveLength:100},
//        scrollClass:"hScrollPane_dragbar5",
//        scrollChildClass:"hScrollPane_draghandle5"
//    });
    $(".quehuobtn").click(function(){
        var skuId=   $(".quehuobtn").attr("skuid");
        if(skuId==""){
            alert("请选择商品规格");
        }
        $.ajax({
            url:webPath.webRoot+"/member/saveProductArrivalNotice.json",
            data:{skuId:skuId},
            dataType: "json",
            success:function(data) {
                var result=data.result;
                if(result=="nologin"){
                    alert("请先登录");
                    goToUrl(webPath.webRoot+"/login.ac");
                    return;

                }
                if(result){
                    alert("登记成功，请耐心等候我们的邮件通知");
                }else{
                    alert("登记成功，请耐心等候我们的邮件通知");
                }
            },
            error:function(XMLHttpRequest, textStatus) {
                if (XMLHttpRequest.status == 500) {
                    var result = eval("(" + XMLHttpRequest.responseText + ")");
                    alert(result.errorObject.errorText);
                }
            }
        });


    });

    var comboselect=$(".combo > h5").find("a").click(function(){
        comboselect.removeClass("cur");
        $(this).addClass("cur");
        var comboid=$(this).attr("comboid");
        $(".combobox").hide();
        $("#combos"+comboid).fadeIn();
    })

    $(".prd_subNum").click(function(){
        $(".boxNum").removeClass("cur");
        var prdNum = $(".prd_num");
        var value=  prdNum.val();
        var num=parseInt(value)-1;
        if(num==0){
            return;
        }
        prdNum.val(num);
        $(".addcart").attr("num",num);
        $(".fenqi_cart").attr("num",num);
    });
    $(".prd_num").change(function(){
        var value= $(this).val();
        var reg=new RegExp("^[1-9]\\d*$");
        if(!reg.test(value)){
            $(this).val(1);return;
        }
        $(".addcart").attr("num",value);
        $(".fenqi_cart").attr("num",value);
    });


    $(".prd_addNum").click(function(){
        $(".boxNum").removeClass("cur");
        var prdNum = $(".prd_num");
        var value=   prdNum.val();
        var num=parseInt(value)+1;
        prdNum.val(num);
        $(".addcart").attr("num",num);
        $(".fenqi_cart").attr("num",num);
    });
    /*搭配购买*/
    /*页面开始加载去除勾选*/
    var clear_dapei_checked = function(){
        $("#dapei").find("input:checked").click(function(){
            $(this).attr("checked", false);
        })
    }();
    /*勾选搭配购买*/
    $("#dapei").find("input").click(function(){
        if($("#dapei_skuprice").val()==""){
            alert("请选择商品规格");
            $(this).attr("checked",false);
            return;
        }
        var dapei_skuprice=parseInt($("#dapei_skuprice").val());

        var price=0.0;
        var num=0;
        $("#dapei").find("input:checked").each(function(){
            price=price+parseInt($(this).val());
            num++;
        })
        var p=price+ dapei_skuprice
        $("#dapeiprice").html(p);
        $("#selectNum").html(num);
    });
    /*搭配购买*/
    $("#mycarousel").jcarousel({
        scroll: 2,
        initCallback: mycarousel_initCallback,
        // This tells jCarousel NOT to autobuild prev/next buttons
        buttonNextHTML: null,
        buttonPrevHTML: null
    });
    function mycarousel_initCallback(carousel) {
        $('#mycarousel-next').bind('click', function() {
            carousel.next();
            return false;
        });

        $('#mycarousel-prev').bind('click', function() {
            carousel.prev();
            return false;
        });
    };
    var imgls=$("#mycarousel").find("a").hover(function(){
        imgls.removeClass("cur");
        $(this).addClass("cur");
        $("#bigsrc").attr("src",$(this).attr("midsrc"));
        $(".jqzoom").attr("href",$(this).attr("bigsrc"));
    },function(){

    })
    $('.jqzoom').jqzoom({
       zoomType: 'standard',
        lens:true,
        preloadImages: true,
        alwaysOn:false,
        xOffset:210
    });
    var selectSpecValues = new Array();
    var allSpecValueIds = new Array();
    var userSpecValueData = new Array();
    if(userSpecData!=null){
        buildData();
    }



    $(".specSelect").find("a").click(function () {

        if ($(this).hasClass("lock")) {
            return;
        }

        if ($(this).hasClass("cur")) {
            $(this).removeClass("cur");
            $(this).find("span").css("display","none")
        } else {
            $(this).parent().parent().find("a").removeClass("cur");
            $(this).parent().parent().find("a").find("span").css("display","none");
            $(this).addClass("cur");
            $(this).find("span").css("display","inline-block")
        }

        var data_values = $(this).attr("data-value");
        var data_value = data_values.split(":");
        var specObject = {specId:parseInt(data_value[0]), specValueId:parseInt(data_value[1])};

        //加入或移除
        pushSelected(specObject);


        var skuDatas = skuData;
        var selectSpecArray = new Array();
        for (var i = 0; i < selectSpecValues.length; i++) {
            //过滤没有包含选择规格值ID的规格组合
            skuDatas = filterSkuDatas(selectSpecValues[i].specValueId, skuDatas);
            //记录选择规格
            for (var spd = 0; spd < userSpecValueData.length; spd++) {
                if (selectSpecValues[i].specValueId == userSpecValueData[spd].specValueId) {
                    selectSpecArray.push(userSpecValueData[spd].specValueNm);
                    break;
                }
            }
        }

        //展示选择的规格
        displaySelectSpecValue(selectSpecArray);

        $(".lock").removeClass("lock");
        var unSelectSpecValue = new Array();

        var filterSpecValueIds = new Array();
        var filterSkuData = skuData;

        for (var i = 0; i < selectSpecValues.length; i++) {
            filterSkuData = filterSkuDatas(selectSpecValues[i].specValueId, filterSkuData);
            var selectSpecIDs = new Array();
            for(var spd=0;spd<=i;spd++){
                selectSpecIDs[spd]=selectSpecValues[spd].specId;
            }
            filterUnSelectSpecValueIds(selectSpecIDs,unSelectSpecValue,filterSkuData,selectSpecValues[i].specValueId);
        }
        var selectSpecValues1 =  selectSpecValues.reverse();
        var filterSkuData1 = skuData;
        for (var i1 = 0; i1 < selectSpecValues1.length; i1++) {
            filterSkuData1 = filterSkuDatas(selectSpecValues1[i1].specValueId, filterSkuData1);
            var selectSpecIDs1 = new Array();
            for(var spd1=0;spd1<=i1;spd1++){
                selectSpecIDs1[spd1]=selectSpecValues1[spd1].specId;
            }
            filterUnSelectSpecValueIds(selectSpecIDs1,unSelectSpecValue,filterSkuData1,selectSpecValues1[i1].specValueId);
        }

        for (var s = 0; s < unSelectSpecValue.length; s++) {
            $(".specSelect").find("a").each(function () {
                var data_value = $(this).attr("data-value");
                var specValueId = parseInt(data_value.split(":")[1]);
                if (unSelectSpecValue[s] == specValueId) {
                    $(this).addClass("lock");
                }
            });
        }

        if (skuDatas.length == 1 && $(".specSelect").size() == selectSpecValues.length) {
            selectSku(skuDatas[0]);
        }else{
            $("#dapei_skuId").val("");
            $("#dapei_skuprice").val("");
            $("#dapeiprice").html("0.0");
            $("#price").html($("#priceListStr").val());
            $(".combo_price").html($("#priceListStr").val());
            $(".addcart").attr("skuid","");
            $(".fenqi_cart").attr("skuid","");
            $(".addTobuyCar").show('');
            $(".quehuo").hide('');
            $("#specialPrice").hide();
            $(".priceNm").html($("#priceListStr").attr("priceNm")+"：")
        }
    });

    function buildData(){
        if(userSpecData == null){
            return;
        }
        for (var spd = 0; spd < userSpecData.length; spd++) {
            var productUserSpec =  userSpecData[spd].specValueProxyList;
            for(var usp=0;usp<productUserSpec.length;usp++){
                var specValueId= productUserSpec[usp].specValueId;
                var userDefinedName= productUserSpec[usp].userDefinedName;
                var name= productUserSpec[usp].name;
                var relPicId= productUserSpec[usp].relPictId;
                var specId= userSpecData[spd].specId;

                allSpecValueIds.push(specValueId);
                userSpecValueData.push({
                    specId:specId,
                    specValueId:specValueId,
                    specValueNm:(userDefinedName!=undefined&&$.trim(userDefinedName).length>0)?userDefinedName:name,
                    relPicId:relPicId
                });
            }
        }
    }

    //根据规格ID取出规格值
    function getUseSpecValue(specValueId){
        for(var i=0;i<userSpecValueData.length;i++){
            if(userSpecValueData[i].specValueId==specValueId){
                return userSpecValueData[i];
            }
        }
    }

    //增加或删除规格
    function pushSelected(specObject) {
        //不是增加 就是 删除
        var isAdd = true;
        var addIndex = -1;
        for (var i = 0; i < selectSpecValues.length; i++) {
            var specValueId = selectSpecValues[i].specValueId;
            var specId = selectSpecValues[i].specId;

            if (specId == specObject.specId) {
                addIndex = i;
                if (specObject.specValueId == specValueId) {
                    isAdd = false;//删除
                    break;
                }
            }
        }
        //增加
        if (isAdd) {
            if (addIndex < 0) {
                selectSpecValues.push(specObject);
            } else {
                selectSpecValues[addIndex] = specObject;
            }
            //显示规格相关图片
            var useSpecValue = getUseSpecValue(specObject.specValueId);
            if(useSpecValue.relPicId!=undefined&&$.trim(useSpecValue.relPicId).length>0){
                displaySpecRefPic(useSpecValue.relPicId)
            }
        }
        //删除
        else {
            //
            selectSpecValues.splice(addIndex, 1);
        }
    }

    //sku过滤器
    function filterSkuDatas(specValueId, skuDatas) {
        var result = new Array();
        for (var i = 0; i < skuDatas.length; i++) {
            if ($.inArray(specValueId, skuDatas[i].specValueIds) >= 0) {
                result.push(skuDatas[i]);
            }
        }
        return result;
    }

    //选择过滤器
    function filterUnSelectSpecValueIds(selectSpecIds,unSelectSpecValue,filterDatas,selectSpecValueId) {
        var canSelects = new Array();
        var filterSpecValueIds = new Array();
        if (selectSpecValueId == undefined) {
            return  unSelectSpecValue;
        }

        for(var us = 0; us < userSpecValueData.length; us++){
            var isSelectSpecId=false;
            for(var spId=0;spId<selectSpecIds.length;spId++){
                if(selectSpecIds[spId]==userSpecValueData[us].specId){
                    isSelectSpecId =true;
                }

            }
            if(!isSelectSpecId){
                filterSpecValueIds.push(userSpecValueData[us].specValueId);
            }
        }


        for (var i = 0; i < filterDatas.length; i++) {
            var specValueIds = filterDatas[i].specValueIds;
            if ($.inArray(selectSpecValueId, specValueIds) >= 0) {
                for(var a=0;a<specValueIds.length;a++){
                    canSelects.push(specValueIds[a]);
                }
            }
        }

        for (var f = 0; f < filterSpecValueIds.length; f++) {
            if ($.inArray(filterSpecValueIds[f], canSelects) < 0) {
                unSelectSpecValue.push(filterSpecValueIds[f]);
            }
        }

        return unSelectSpecValue;
    }

    //收藏商品
    $("#AddTomyLikeBtn").click(function(){
        if(webPath.productId == '' || webPath.productId == undefined){
            return ;
        }
        $.get(webPath.webRoot+"/member/collectionProduct.json?productId="+webPath.productId,function(data){
            if(data.success == false){
                if(data.errorCode == "errors.login.noexist"){
                    if(confirm("您尚未登陆，请登陆!")){
                        goToUrl(webPath.webRoot+"/login.ac");
                    }
                    return;
                }
                if(data.errorCode == "errors.collection.has"){
                    $(".AddTomyLikeLayer .showTip .succe h3").html("您已经收藏了此商品！");
                    $(".AddTomyLikeLayer").show();
                    return;
                }
            }else if(data.success == true){
                var collectCount;
                if(webPath.productCollectCount == '' || webPath.productCollectCount == undefined){
                    collectCount = 1
                }else{
                    collectCount = parseInt(webPath.productCollectCount)+1
                }
                $("#productCollectCount").html(collectCount);
                $(".AddTomyLikeLayer .showTip .succe h3").html("商品已成功收藏！");
                $(".AddTomyLikeLayer").show();
                return;
            }
        });
    });

    //多规格默认选中
    $(".specSelect").each(function(){
        $(this).find("li:first a:first").each(function(){
            this.click();
        });
    });
    //滚动条
    $('#scrollbar2').tinyscrollbar({ axis: 'x'});
    $('#combosScrollbar').tinyscrollbar({ axis: 'x'});
});

//显示规格关联图片
function displaySpecRefPic(pic){
    $("#mycarousel").find("a").each(function(){
        var rel = eval("(" + $.trim($(this).attr('rel')) + ")");
        if(pic==$(this).attr("picId")){
            $("#bigsrc").attr("src",rel.smallimage);
            $(".jqzoom").attr("href",rel.largeimage);
        }
    });
}

//显示已选择的规格值
function displaySelectSpecValue(nameArray){
    $("#selecSpec").html("已选择:");
    $("#specValue").html("");
    for(var i=0;i<nameArray.length;i++){
        if (i != 0) {
            $("#selecSpec").append("、");
            $("#specValue").append("、");
        }
        $("#selecSpec").append("  <b>" + "\"" + nameArray[i] + "\"" + " </b> ");
        $("#specValue").append("  <b>" + "\"" + nameArray[i] + "\"" + " </b> ");
    }
}

//选择多种规格后得到SKU
function selectSku(skuData) {
    var sku = skuData.sku;
    var price = skuData.price;
    if(sku.currentNum==0 || sku.currentNum<=sku.safetyStock ){
        $(".addTobuyCar").hide('');

        $(".quehuo").show('');
        $(".quehuobtn").attr("skuid",sku.skuId);
        return;
    }

    //显示价格
    $("#price").html(price.unitPrice);
    $(".combo_price").html(price.unitPrice);
    $("#dapeiprice").html(price.unitPrice);
    $("#dapei_skuId").val(sku.skuId);
    $("#dapei_skuprice").val(price.unitPrice);
    $(".addcart").attr("skuid",sku.skuId);
    $(".fenqi_cart").attr("skuid",sku.skuId);

    //组合套餐
    if(price.isSpecialPrice){
        $("#specialPrice").show();
        $("#lesTime").imallCountdown(price.endTimeStr,"li",webPath.systemTime);
        $(".priceNm").html(price.amountNm+"：")
    }else{
        $("#specialPrice").hide();
        $(".priceNm").html(price.amountNm+"：")
    }

}

//清空商品的cookie
var clearHistoryProductsCookie = function(divId){
    $.get(webPath.webRoot+"/member/clearProductsCookie.json",function(data){
        $(divId).html("<div class='m3-info'' style='text-align: center;height: 30px;padding-top: 10px;'>您还未浏览其它商品</div>");
    });
};

function tabChance(tabIndex,showObj){
    $(".minute_menu2 a").removeClass("cur");
    $($(".minute_menu2 a")[tabIndex]).addClass("cur");
    $(".m2r_info").hide();
    $(showObj).fadeIn();
}

function chanceNum(obj,num){
    $(".boxNum").removeClass("cur");
    $(obj).addClass("cur");
    var prdNum = $(".prd_num");
    prdNum.val(num);
    $(".addcart").attr("num",num);
    $(".fenqi_cart").attr("num",num);
}

